package com.hivekion.common.security;

import com.hivekion.common.entity.vo.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * Security相关操作
 *
 * @author Louis
 * @date Jun 29, 2019
 */
public class SecurityUtils {

      /**
       * 获取令牌进行认证
       *
       * @param request
       */
      public static Authentication checkAuthentication(HttpServletRequest request) {
	    Authentication authentication =
		    JwtTokenUtils.getAuthenticationeFromToken(request); // 获取令牌并根据令牌获取登录认证信息
	    return authentication;
      }

      /**
       * 获取当前用户名
       *
       * @return
       */
      public static String getUsername() {
	    Authentication authentication = getAuthentication();
	    return getUsername(authentication);
      }

      /**
       * 获取用户名
       *
       * @return
       */
      public static String getUsername(Authentication authentication) {
	    LoginUser user = getLoginUser(authentication);
	    if (user != null) {
			return user.getUsername();
		}
	    return null;
      }

      public static LoginUser getCurrentLoginUser() {
	    Authentication authentication = getAuthentication();
	    return getLoginUser(authentication);
      }

      public static LoginUser getLoginUser(Authentication authentication) {
	    if (authentication != null) {
		  Object principal = authentication.getPrincipal();
		  if (principal != null && principal instanceof LoginUser) {
			return (LoginUser) principal;
		  }
	    }
	    return null;
      }

      public static String getUserId(Authentication authentication) {
	    LoginUser user = getLoginUser(authentication);
	    if (user != null) {
			return user.getUserId();
		}
	    return null;
      }

      /**
       * 获取当前登录信息
       *
       * @return
       */
      public static Authentication getAuthentication() {
	    if (SecurityContextHolder.getContext() == null) {
		  return null;
	    }
	    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	    return authentication;
      }
}
